<?php

define('BASE_URL', "http://" . $_SERVER["SERVER_NAME"] . "/");
define('TEMPLATE_BASE_URL', BASE_URL . "index.php?publicToken=");
define('EDIT_BASE_URL', BASE_URL . "index.php?privateToken=");
define('SHOW_DESIGN_BASE_URL', BASE_URL . "show_design.php?publicToken=");

function connectToDb() {
    require_once("config.php");
    @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("DB error - could not connect to server");
    @mysql_select_db(DB_NAME) or die("DB error - could not select database");
}

function getDesignFromPublicToken($publicToken) {
    return getDesignWithWhere("public_token = '" . $publicToken . "'");
}

function getDesignFromPrivateToken($privateToken) {
    return getDesignWithWhere("private_token = '" . $privateToken . "'");
}

function getDesignWithWhere($whereQuery) {
    $query =
       "SELECT id, name, content, is_template, is_featured, user_id, description, author, public_token, private_token, image, thumbnail_image, created_date, edited_date, size_length, size_width 
        FROM design 
        WHERE " . $whereQuery;
    $result = mysql_query($query);
    if (mysql_num_rows($result) == 0) {
        return false;
    }
    else {
        return mysql_fetch_assoc($result);
    }
}

function getFeaturedDesigns($limit = 5) {
    $output = array();
    
    $query =
       "SELECT id, name, content, is_template, is_featured, user_id, description, author, public_token, private_token, image, thumbnail_image, created_date, edited_date, size_length, size_width 
        FROM design 
        WHERE is_featured = 1
        ORDER BY created_date DESC
        LIMIT " . $limit;
    $result = mysql_query($query);
    if (mysql_num_rows($result) > 0) {
        while ($row = mysql_fetch_assoc($result)) {
            $output[] = $row;
        }
    }
    
    return $output;
}

function sendEmail($toAddress, $title, $content) {
    $fromAddress = "noreply@invitationstation.org";
    
    $emailHeaders = "From: " . $fromAddress . "\r\n";
    $emailHeaders .= "MIME-Version: 1.0\r\n";
    $emailHeaders .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

    $emailHtml = '<html><body style="font-family: Tahoma, Verdana;"><div>'
          . $content
          . '</div></body></html>';
    
    if (SEND_EMAILS) {
        mail(
            $toAddress,
            $title,
            $emailHtml,
            $emailHeaders
        );
    }
}

